/**
 * 颜色选择器工具 JavaScript
 */

document.addEventListener('DOMContentLoaded', function() {
    // 引入ClipboardJS库
    const ClipboardJS = window.ClipboardJS;
    // 初始化复制按钮
    const clipboard = new ClipboardJS('.copy-btn');
    clipboard.on('success', function(e) {
        const originalText = e.trigger.innerHTML;
        e.trigger.innerHTML = '<i class="feather-check"></i>';
        setTimeout(function() {
            e.trigger.innerHTML = originalText;
        }, 1500);
        e.clearSelection();
    });

    // 获取DOM元素
    const colorPicker = document.getElementById('colorPicker');
    const hexColor = document.getElementById('hexColor');
    const rgbColor = document.getElementById('rgbColor');
    const hslColor = document.getElementById('hslColor');
    const hwbColor = document.getElementById('hwbColor');
    const lchColor = document.getElementById('lchColor');
    const cmykColor = document.getElementById('cmykColor');
    const colorName = document.getElementById('colorName');
    const colorPreview = document.getElementById('colorPreview');

    // 初始化高级颜色选择器
    const pickr = Pickr.create({
        el: '#colorPickerAdvanced',
        theme: 'classic',
        default: '#1ea54c',
        swatches: [
            '#f44336', '#E91E63', '#9C27B0', '#673AB7',
            '#3F51B5', '#2196F3', '#03A9F4', '#00BCD4',
            '#009688', '#4CAF50', '#8BC34A', '#CDDC39',
            '#FFEB3B', '#FFC107', '#FF9800', '#FF5722',
            '#795548', '#9E9E9E', '#607D8B', '#000000'
        ],
        components: {
            preview: true,
            opacity: true,
            hue: true,
            interaction: {
                hex: true,
                rgba: true,
                hsla: true,
                input: true,
                clear: false,
                save: true
            }
        }
    });

    // 颜色选择器事件
    colorPicker.addEventListener('input', function() {
        updateAllColors(this.value);
    });

    // 高级颜色选择器事件
    pickr.on('change', function(color) {
        const hexValue = color.toHEXA().toString();
        updateAllColors(hexValue);
        colorPicker.value = hexValue;
    });

    // 输入框事件监听
    hexColor.addEventListener('input', function() {
        try {
            if (isValidHex(this.value)) {
                updateAllColors(this.value);
                colorPicker.value = this.value;
            }
        } catch (e) {
            console.error('Invalid hex color:', e);
        }
    });

    rgbColor.addEventListener('input', function() {
        try {
            const hex = rgbToHex(this.value);
            if (hex) {
                updateAllColors(hex);
                colorPicker.value = hex;
            }
        } catch (e) {
            console.error('Invalid RGB color:', e);
        }
    });

    hslColor.addEventListener('input', function() {
        try {
            const hex = hslToHex(this.value);
            if (hex) {
                updateAllColors(hex);
                colorPicker.value = hex;
            }
        } catch (e) {
            console.error('Invalid HSL color:', e);
        }
    });

    // 更新所有颜色格式
    function updateAllColors(hexValue) {
        if (!hexValue) return;
        
        // 更新预览
        colorPreview.style.backgroundColor = hexValue;
        
        // 更新各种格式
        hexColor.value = hexValue;
        rgbColor.value = hexToRgb(hexValue);
        hslColor.value = hexToHsl(hexValue);
        hwbColor.value = hexToHwb(hexValue);
        lchColor.value = hexToLch(hexValue);
        cmykColor.value = hexToCmyk(hexValue);
        colorName.value = getColorName(hexValue);
        
        // 更新高级选择器
        pickr.setColor(hexValue);
    }

    // 检查是否为有效的十六进制颜色
    function isValidHex(hex) {
        return /^#([0-9A-F]{3}){1,2}$/i.test(hex);
    }

    // 十六进制转RGB
    function hexToRgb(hex) {
        // 移除#号并标准化为6位
        hex = hex.replace('#', '');
        if (hex.length === 3) {
            hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
        }
        
        const r = parseInt(hex.substring(0, 2), 16);
        const g = parseInt(hex.substring(2, 4), 16);
        const b = parseInt(hex.substring(4, 6), 16);
        
        return `rgb(${r}, ${g}, ${b})`;
    }

    // RGB转十六进制
    function rgbToHex(rgb) {
        const match = rgb.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i);
        if (!match) return null;
        
        const r = parseInt(match[1]);
        const g = parseInt(match[2]);
        const b = parseInt(match[3]);
        
        return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
    }

    // 十六进制转HSL
    function hexToHsl(hex) {
        // 移除#号
        hex = hex.replace('#', '');
        if (hex.length === 3) {
            hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
        }
        
        let r = parseInt(hex.substring(0, 2), 16) / 255;
        let g = parseInt(hex.substring(2, 4), 16) / 255;
        let b = parseInt(hex.substring(4, 6), 16) / 255;
        
        const max = Math.max(r, g, b);
        const min = Math.min(r, g, b);
        let h, s, l = (max + min) / 2;
        
        if (max === min) {
            h = s = 0; // 灰色
        } else {
            const d = max - min;
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
            
            switch (max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }
            
            h /= 6;
        }
        
        h = Math.round(h * 360);
        s = Math.round(s * 100);
        l = Math.round(l * 100);
        
        return `hsl(${h}, ${s}%, ${l}%)`;
    }

    // HSL转十六进制
    function hslToHex(hsl) {
        const match = hsl.match(/^hsl\s*\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$/i);
        if (!match) return null;
        
        let h = parseInt(match[1]) / 360;
        let s = parseInt(match[2]) / 100;
        let l = parseInt(match[3]) / 100;
        
        let r, g, b;
        
        if (s === 0) {
            r = g = b = l; // 灰色
        } else {
            const hue2rgb = (p, q, t) => {
                if (t < 0) t += 1;
                if (t > 1) t -= 1;
                if (t < 1/6) return p + (q - p) * 6 * t;
                if (t < 1/2) return q;
                if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
                return p;
            };
            
            const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
            const p = 2 * l - q;
            
            r = hue2rgb(p, q, h + 1/3);
            g = hue2rgb(p, q, h);
            b = hue2rgb(p, q, h - 1/3);
        }
        
        const toHex = x => {
            const hex = Math.round(x * 255).toString(16);
            return hex.length === 1 ? '0' + hex : hex;
        };
        
        return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
    }

    // 十六进制转HWB
    function hexToHwb(hex) {
        // 移除#号
        hex = hex.replace('#', '');
        if (hex.length === 3) {
            hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
        }
        
        const r = parseInt(hex.substring(0, 2), 16) / 255;
        const g = parseInt(hex.substring(2, 4), 16) / 255;
        const b = parseInt(hex.substring(4, 6), 16) / 255;
        
        const max = Math.max(r, g, b);
        const min = Math.min(r, g, b);
        let h, w = min, bl = 1 - max;
        
        if (max === min) {
            h = 0; // 灰色
        } else {
            const d = max - min;
            
            switch (max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }
            
            h /= 6;
        }
        
        h = Math.round(h * 360);
        w = Math.round(w * 100);
        bl = Math.round(bl * 100);
        
        return `hwb(${h} ${w}% ${bl}%)`;
    }

    // 十六进制转LCH
    function hexToLch(hex) {
        // 简化实现，实际应该使用专业的颜色转换库
        // 这里提供一个近似值
        const rgb = hexToRgb(hex);
        const match = rgb.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i);
        
        if (!match) return "lch(0% 0 0)";
        
        const r = parseInt(match[1]) / 255;
        const g = parseInt(match[2]) / 255;
        const b = parseInt(match[3]) / 255;
        
        // 简化的RGB到LCH转换
        // 实际应该使用更复杂的算法
        const l = Math.round((0.2126 * r + 0.7152 * g + 0.0722 * b) * 100);
        const c = Math.round(Math.sqrt(Math.pow(r - g, 2) + Math.pow(g - b, 2) + Math.pow(b - r, 2)) * 100);
        const h = Math.round(Math.atan2(b - g, r - g) * (180 / Math.PI));
        
        return `lch(${l}% ${c.toFixed(2)} ${h.toFixed(2)})`;
    }

    // 十六进制转CMYK
    function hexToCmyk(hex) {
        // 移除#号
        hex = hex.replace('#', '');
        if (hex.length === 3) {
            hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
        }
        
        let r = parseInt(hex.substring(0, 2), 16) / 255;
        let g = parseInt(hex.substring(2, 4), 16) / 255;
        let b = parseInt(hex.substring(4, 6), 16) / 255;
        
        let k = 1 - Math.max(r, g, b);
        let c = k === 1 ? 0 : (1 - r - k) / (1 - k);
        let m = k === 1 ? 0 : (1 - g - k) / (1 - k);
        let y = k === 1 ? 0 : (1 - b - k) / (1 - k);
        
        c = Math.round(c * 100);
        m = Math.round(m * 100);
        y = Math.round(y * 100);
        k = Math.round(k * 100);
        
        return `device-cmyk(${c}% ${m}% ${y}% ${k}%)`;
    }

    // 获取颜色名称（简化实现）
    function getColorName(hex) {
        // 这里只实现了一些基本颜色
        // 实际应该使用颜色名称库
        const colorMap = {
            '#FF0000': 'red',
            '#00FF00': 'lime',
            '#0000FF': 'blue',
            '#FFFF00': 'yellow',
            '#00FFFF': 'cyan',
            '#FF00FF': 'magenta',
            '#000000': 'black',
            '#FFFFFF': 'white',
            '#808080': 'gray',
            '#800000': 'maroon',
            '#808000': 'olive',
            '#008000': 'green',
            '#800080': 'purple',
            '#008080': 'teal',
            '#000080': 'navy',
            '#FFA500': 'orange',
            '#A52A2A': 'brown',
            '#FFC0CB': 'pink',
            '#1EA54C': 'seagreen'
        };
        
        // 标准化十六进制颜色
        hex = hex.toUpperCase();
        
        return colorMap[hex] || 'custom';
    }

    // 初始化颜色
    updateAllColors('#1ea54c');
});